package lib.bone.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.system.event.AuthRoleEvent;
import lib.bone.system.service.SysRoleService;
import lib.bone.system.service.SysUserRoleService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * @author: kindear
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "用户授权管理")
public class SysUserRoleController {
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired(required = false)
    AuthRoleEvent authRoleEvent;



    /**
     * 批量授权角色用户 -- 在该接口写一个触发事件
     */
    @WebLog(module = "bone-system")
    @PutMapping("roles/{roleId}/users")
    @ApiOperation(value = "角色赋权(多用户)",notes = "")
    @SaCheckRole("admin")
    public ResponseDTO batchAuthRoleUser(@PathVariable("roleId") Long roleId, @RequestParam("userIds") List<Long> userIds) {
        log.info(userIds.toString());
        userIds.forEach(userId->{
            authRoleEvent.process(roleId,userId);
        });
        return sysUserRoleService.grantRoleUsers(roleId, userIds);
    }

    /**
     * 删除用户授权
     */
    @WebLog(module = "bone-system",operate = MethodTypeConst.DELETE)
    @ApiIgnore
    @DeleteMapping("roles/{roleId}/users/{userId}")
    @ApiOperation(value = "取消角色授权",notes = "")
    @SaCheckRole("admin")
    public ResponseDTO cancelRoleUser(@PathVariable("roleId") Long roleId,@PathVariable("userId") Long userId){
        return sysUserRoleService.cancelRoleUser(roleId,userId);
    }

    /**
     * 删除用户授权
     */
    @WebLog(module = "bone-system",operate = MethodTypeConst.DELETE)
    @PostMapping("authorization/cancel")
    @ApiOperation(value = "取消授权",notes = "传入roleId 和 userId")
    @SaCheckRole("admin")
    public ResponseDTO cancelAuthorization(@RequestParam("roleId") Long roleId,@RequestParam("userId") Long userId){
        return sysUserRoleService.cancelRoleUser(roleId,userId);
    }

    /**
     * 修改授权角色信息
     * @param userId
     * @param roleIds
     * @return
     */
    @WebLog(module = "bone-system")
    @PutMapping("users/{userId}/roles")
    @ApiOperation(value = "多角色赋权(单用户)")
    @SaCheckRole("admin")
    public ResponseDTO grantUserRoles(@PathVariable("userId") Long userId,@RequestParam("roleIds") List<Long> roleIds){
        return sysUserRoleService.grantUserRoles(userId,roleIds);
    }


}
